/*
 * @Author: asushiye
 * @Date: 2020-07-02 15:30:23
 * @Commit: file content
 */
import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { AfMessageService } from '@core';
import { STColumn, STComponent } from '@delon/abc/st';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { AfOperType } from 'src/app/core/af/af-const';
import { AfExcelService, ExcelUploadRecord } from 'src/app/routes/system/excel/af-excel.service';
import { ExcelUploadComponent } from 'src/app/routes/system/excel/upload/excel-upload.component';

import { CgDataSourceService } from './cg-datasource.service';
import { CodeGenService } from '../../codegen.service';

@Component({
  selector: 'app-cg-datasource',
  templateUrl: './cg-datasource.component.html'
})
export class CgDatasourceComponent implements OnInit {
  rows: any[] = [];
  queryParams: any = { dbSourceName: '' };
  isLoading = false;
  isExport = false;
  isImport = false;
  afOperType = AfOperType.add;
  databases: any[] = [];

  uploadRecord: ExcelUploadRecord = {
    currentQueueId: '',
    business: 'cg-datasource',
    title: '数据源',
    showExtendedFields: false,
    action: 'save',
    sourceId: '1',
    remark: ''
  };

  @ViewChild('st', { static: false }) st!: STComponent;
  columns: STColumn[] = [
    { title: '数据源', index: 'dbSourceName' },
    { title: '类型', index: 'dbType' },
    { title: '主机', index: 'host' },
    { title: '端口', index: 'port' },
    { title: '数据库', index: 'dbName' },
    {
      title: '操作',
      buttons: [
        {
          text: '测试链接',
          icon: 'link',
          tooltip: `手动测试链接`,
          click: _record => {
            this.testLink(_record);
          }
        },
        {
          text: '编辑',
          icon: 'edit',
          tooltip: `手动测试链接`,
          click: _record => {
            this.edit(_record);
          }
        },
        {
          text: '删除',
          icon: 'delete',
          type: 'del',
          tooltip: `删除此记录`,
          pop: {
            title: '您确定要删除此记录吗？',
            okType: 'danger',
            icon: 'star'
          },
          click: (record, _modal) => {
            this.delete(record);
          }
        }
      ]
    }
  ];

  caseStatusName(status: any) {
    if (status == 0) {
      return '小写';
    }
    if (status == 1) {
      return '原样';
    }
    if (status == 2) {
      return '大写';
    }
    return '小写';
  }

  constructor(
    private cdr: ChangeDetectorRef,
    public msg: AfMessageService,
    private datasource: CgDataSourceService,
    private modal: ModalHelper,
    private excelSrv: AfExcelService,
    private codeGen: CodeGenService
  ) {
    this.queryDatabases();
  }
  ngOnInit() {
    this.query();
  }

  public queryDatabases() {
    this.codeGen.queryDataBaseAll().subscribe(res => {
      console.log(res);
      if (res.status) {
        this.databases = res.data;
      }
    });
  }

  public query() {
    this.isLoading = true;
    this.cdr.detectChanges();
    try {
      this.datasource.query(this.queryParams.dbSourceName).subscribe(body => {
        if (body.status) {
          this.rows = [];
          this.rows = body.data;
        } else {
          this.msg.notice_warning('查询文件', `警告编号${body.code};  警告信息${body.msg}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.isLoading = false;
        this.cdr.detectChanges();
      }, 200);
    }
  }

  importData() {
    this.uploadRecord.currentQueueId = 0;
    const record = this.uploadRecord as any;
    this.modal.create(ExcelUploadComponent, { record }, { size: 'md' }).subscribe(res => {
      if (res.status) {
        this.uploadRecord.currentQueueId = res.data;
        this.query();
      }
    });
  }

  isExporting = false;
  exportData() {
    try {
      this.isExporting = true;
      this.excelSrv.exportData(this.uploadRecord, this.queryParams);
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
        this.isExporting = false;
      }, 1500);
    }
  }

  isLogExporting = false;
  exportLog() {
    try {
      this.isLogExporting = true;
      this.excelSrv.exportLog(this.uploadRecord);
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
        this.isLogExporting = false;
      }, 1500);
    }
  }

  downloadTemplate() {
    this.cdr.detectChanges();
    try {
      this.excelSrv.downTemplateFile(this.uploadRecord);
    } finally {
      this.cdr.detectChanges();
    }
  }

  navUploadLogView() {
    this.excelSrv.navUploadLogView(this.uploadRecord);
  }

  delete(item: any) {
    try {
      this.datasource.delete(item.dbSourceName).subscribe(body => {
        if (body.status) {
          this.rows = [];
          this.msg.notice_success('删除记录', `${item.dbSourceName} 记录删除成功`);
          this.query();
        } else {
          this.msg.notice_warning('删除记录', `${item.dbSourceName} 归档失败，警告编号${body.code};  警告信息${body.msg}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
      }, 200);
    }
  }

  testLink(item: any) {
    try {
      this.datasource.testLink(item.dbSourceName).subscribe(body => {
        if (body.status) {
          this.msg.notice_success('测试链接', `${item.dbSourceName} 链接成功`);
        } else {
          this.msg.notice_warning('测试链接', `${item.dbSourceName} 链接失败，警告编号${body.code};  警告信息${body.msg}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
      }, 200);
    }
  }

  testLinkClick() {
    this.datasource.testLinkClick(this.tForm.getRawValue()).subscribe(body => {
      if (body.status) {
        this.msg.notice_success('', `链接成功`);
      } else {
        this.msg.notice_error('链接失败', `失败信息：${body.msg}`);
      }
    });
  }

  public dbTypeChange(event: any) {
    const database = this.databases.filter(item => item.dataBase == event);
    if (database && database.length >= 1) {
      console.log(database[0]);
      this.tForm.controls.driverClassName.patchValue(database[0].driverClassName);
    }
    this.setDbLinkTypeAndSchemaControls(event);
  }

  setDbLinkTypeAndSchemaControls(dbLink: any) {
    if (dbLink == 'oracle') {
      if (!this.tForm.controls.dbLinkType.value) {
        this.tForm.controls.dbLinkType.patchValue('server');
        this.schemaName = 'server';
      } else {
        this.schemaName = this.tForm.controls.dbLinkType.value;
      }
      this.tForm.controls.dbLinkType.enable();
    } else {
      this.schemaName = 'schema';
      this.tForm.controls.dbLinkType.disable();
    }

    if (dbLink == 'oracle' || dbLink == 'postgresql' || dbLink == 'sqlserver') {
      this.tForm.controls.dbSchema.enable();
    } else {
      this.tForm.controls.dbSchema.disable();
    }
    if (dbLink == 'postgresql') {
      this.tForm.controls.dbSchema.setValue('public');
    } else if (dbLink == 'sqlserver') {
      this.tForm.controls.dbSchema.setValue('dbo');
    }
  }

  schemaName: any = 'schema';
  public dbLinkTypeChange(event: any) {
    this.schemaName = event;
  }

  autoTips: Record<string, Record<string, string>> = {
    'zh-cn': {
      required: '必填项'
    },
    en: {
      required: 'Input is required'
    }
  };

  tForm = new FormGroup({
    dbSourceName: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
    dbSourceDesc: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
    dbType: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
    dbLinkType: new FormControl(''),
    driverClassName: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
    dbName: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
    host: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
    port: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
    dbSchema: new FormControl(''),
    username: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
    password: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
    caseStatus: new FormControl(0, { nonNullable: true, validators: [Validators.required] }),
    extParams: new FormControl('')
  });

  drawerOption: any = { size: 'large', visible: false, title: '编辑' };
  openDrawer() {
    this.drawerOption.visible = true;
    if (this.afOperType == AfOperType.edit) {
      this.tForm.controls.dbSourceName.disable();
      this.tForm.controls.dbType.disable();
    } else {
      this.tForm.controls.dbSourceName.enable();
      this.tForm.controls.dbType.enable();
    }
  }

  closeDrawer() {
    this.drawerOption.visible = false;
  }

  save() {
    if (this.tForm.invalid) {
      this.msg.notice_warning('警告', '表单无效不能保存');
      return;
    }
    this.datasource.save(this.tForm.getRawValue()).subscribe(res => {
      if (res.status) {
        this.query();
        this.msg.notice_success('', '保存成功');
        this.closeDrawer();
      } else {
        this.msg.notice_warning('保存失败', res.msg);
      }
    });
  }

  add() {
    this.afOperType = AfOperType.add;
    this.tForm.reset();
    this.tForm.controls.dbLinkType.disable();
    // this.tForm.controls.dbSchema.disable();
    this.openDrawer();
  }

  edit(item: any) {
    this.afOperType = AfOperType.edit;
    this.tForm.reset();
    this.tForm.patchValue(item);
    this.setDbLinkTypeAndSchemaControls(item.dbType);
    this.openDrawer();
  }
}
